package com.tticar.invmanager.common.config;

import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * Created by yandou on 2018/6/13.
 */
@Configuration
@MapperScan(basePackages = {"com.tticar.invmanager.tticar.mapper"}, sqlSessionFactoryRef = "ttMybatisSqlSession")
public class TticarMybatisPlusConfig {

    @Bean("ttDatasource")
    @ConfigurationProperties("tt.datasource")
    public HikariDataSource secondDataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean("ttMybatisSqlSession")
    public SqlSessionFactory ttMybatisSqlSession() throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(secondDataSource());
        sqlSessionFactory.setTypeAliasesPackage("com.tticar.invmanager.tticar.entity");
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/tticar/*.xml"));
        sqlSessionFactory.setPlugins(new Interceptor[]{
                paginationInterceptor()
        });
        return sqlSessionFactory.getObject();
    }

    @Bean("ttSqlSessionLocalTemplate")
    public SqlSessionTemplate ttSqlSessionLocalTemplate() throws Exception {
        return new SqlSessionTemplate(ttMybatisSqlSession());
    }

    @Bean("ttTransactionManager")
    public PlatformTransactionManager ttTransactionManager() {
        return new DataSourceTransactionManager(secondDataSource());
    }

    private Interceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setLocalPage(true);// 开启 PageHelper 的支持
        return paginationInterceptor;
    }

    @Bean(name = "ttDataSourceTransactionManager")
    public DataSourceTransactionManager ttDataSourceTransactionManager() {
        return new DataSourceTransactionManager(secondDataSource());
    }

    @Bean("ttrSqlSessionTemplate")
    public SqlSessionTemplate ttrSqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(ttMybatisSqlSession());
    }

}
